package com.llh.demo4minio.controller

import io.minio.MinioClient
import io.minio.PutObjectOptions
import org.springframework.beans.factory.annotation.Value
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.multipart.MultipartFile
import java.util.*
import javax.annotation.PostConstruct

/**
 *
 * <p>CreatedAt: 2020/9/16 10:15</p>
 * @author llh
 */
@RestController
@RequestMapping("file")
class FileController {
    val bucketName = "test-bucket"

    private lateinit var mc: MinioClient

    @Value("\${nginx.server}")
    private lateinit var fileServer:String

    @PostConstruct
    fun init() {
        val endpoint = "http://127.0.0.1:9000"
        val accessKeyID = "minioadmin"
        val secretAccessKey = "minioadmin"
        val useSSL = false
        mc = MinioClient(endpoint, accessKeyID, secretAccessKey, useSSL)
    }

    @PostMapping("avatar")
    fun avatar(@RequestParam("file") file: MultipartFile): Any {

        // 存储对象名不能以 / 开头
        val objectName = "avatar/" + UUID.randomUUID().toString() + "." + extName(file.originalFilename!!)
        val options = PutObjectOptions(
                file.size, // or -1 , auto handle file size
                PutObjectOptions.MIN_MULTIPART_SIZE.toLong())
        mc.putObject(bucketName, objectName, file.inputStream, options)

        return mapOf(
                "file_name" to "$bucketName/$objectName",
                "src" to "$fileServer/$bucketName/$objectName"
        )
    }

    /**
     * 取出拓展名的简单方法
     */
    private fun extName(fileName: String): String {
        return fileName.split(".")[1]
    }
}